package com.business.dynamic.controller;


import com.alibaba.fastjson.JSONObject;
import com.business.common.dto.R;
import com.business.dynamic.entity.DynamicContentTemplate;
import com.business.dynamic.service.DynamicContentTemplateService;
import com.business.redis.ExpiresTimeEnum;
import com.business.redis.constant.RedisKeyConstant;
import com.business.redis.utils.RedisUtil;
import com.business.user.annotation.TokenPermission;
import com.business.user.entity.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 内容模板表: 后端controller类
 *
 * @author chenjiehong
 * @date 2019-11-29 15:15:38
 * @since 1.0
 */
@RestController
@RequestMapping(value = "/contentTemplate")
public class DynamicContentTemplateController {


    @Autowired
    private DynamicContentTemplateService dynamicContentTemplateServiceImpl;


    /**
     * 查询内容模板表
     *
     * @param params
     * @date 2019-11-29 15:15:38
     */
    @PostMapping("/query")
    @ResponseBody
    @TokenPermission
    public R query(@RequestBody JSONObject params, UserDto user) {
        Integer id = params.getInteger("id");
        String key = String.format(RedisKeyConstant.DYNAMIC_CONTENT_TEMPLATE_QUERY, id);
        if (RedisUtil.hasKey(key)) {
            return R.success(RedisUtil.getObject(key, DynamicContentTemplate.class));
        } else {
            DynamicContentTemplate r = dynamicContentTemplateServiceImpl.query(id);
            RedisUtil.setValue(key, r, ExpiresTimeEnum.LEVEL_8.getExpiresTime());
            return R.success(r);
        }
    }


    /**
     * 查询内容模板表
     *
     * @param params
     * @date 2019-11-29 15:15:38
     */
    @PostMapping("/queryList")
    @ResponseBody
    @TokenPermission
    public R queryList(@RequestBody JSONObject params) {
        Integer type = params.getInteger("type");
        String parentCategoryCode = params.getString("parentCategoryCode");
        String subCategoryCode = params.getString("subCategoryCode");
        String key = String.format(RedisKeyConstant.DYNAMIC_CONTENT_TEMPLATE_QUERY_LIST, parentCategoryCode, subCategoryCode);
        if (RedisUtil.hasKey(key)) {
            return R.success(RedisUtil.getArray(key, DynamicContentTemplate.class));
        } else {
            List<DynamicContentTemplate> r = dynamicContentTemplateServiceImpl.queryList(type, parentCategoryCode, subCategoryCode);
            RedisUtil.setValue(key, r, ExpiresTimeEnum.LEVEL_8.getExpiresTime());
            return R.success(r);
        }
    }

}